﻿using Application.Users.Commands.CreateUser;
using Application.Users.Commands.DeleteUser;
using Application.Users.Commands.UpdateUser;
using Application.Users.Models;
using Application.Users.Queries.GetUser;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Shared.Http.APIResult;

namespace WebApi.Controllers;

[ApiController]
[Route("/api/v2/users")]
public class UserController(
    IMediator mediator) : ControllerBase
{
    #region RestFul

    [HttpGet]
    [Route("{id}")]
    public async Task<ActionResult<IReadOnlyCollection<GetUserModel>>> GetUser(Guid id)
    {
        var users = await mediator.Send(new GetUserFilter()
        {
            Ids = [id],
            PageNo = 1,
            PageSize = 1
        }, default);
        return Ok(ApiResult.Success(users, Guid.NewGuid()));
    }

    [HttpDelete]
    [Route("{id}")]
    public async Task<ActionResult<ApiResult<Guid>>> DeleteUser(Guid id)
    {
        var result = await mediator.Send(new DeleteUserCommand([id]));
        return Ok(ApiResult.Success(result, Guid.NewGuid()));
    }

    [HttpPut]
    [Route("{id}")]
    public async Task<ApiResult<Guid>> UpdateUser(Guid id, [FromBody] UpdateUserModel request)
    {
        var result = await mediator.Send(new UpdateUserCommand([request]));

        //TODO
        return new()
        {
            Code = result.IsSuccess ? ApiStatusCode.Success : ApiStatusCode.BusinessError,
            Errors = result?.Errors.Select(e => new ErrorData(e.Id ?? string.Empty, e.Message))?.ToList(),
            TraceId = Guid.NewGuid()
        };
    }

    [HttpPost]
    public async Task<ApiResult<Guid>> CreateUser(CreateUserModel request)
    {
        var result = await mediator.Send(new CreateUserCommand([request]));
        //TODO
        return new()
        {
            Code = result.IsSuccess ? ApiStatusCode.Success : ApiStatusCode.BusinessError,
            Data = result.IsSuccess ? result?.Data?.FirstOrDefault() ?? Guid.Empty : Guid.Empty,
            Errors = result?.Errors.Select(e => new ErrorData(e.Id ?? string.Empty, e.Message))?.ToList(),
            TraceId = Guid.NewGuid()
        };
    }
    #endregion
}